package test;

import java.io.IOException;
//import java.util.HashMap;
import java.util.Iterator;
//import java.util.Map;


public class MagentoImportManager extends ImportManager{

	public MagentoImportManager (Params params) {
		super(params);
		//parseCSV();
	}
	//private static final String primKey = "sku";	
	private String primKey = "sku";
	//private String indexes = "";
		//private String lastRecord ="";
	private int lastRecord =-1;
	private DWCatalog xmlCatalog=null;
/*	
	protected void appendLine(CSVLine line) {
		//indexes.split(",");
		
		String prim = line.getField(primKey);
		if ("".equalsIgnoreCase(prim) || prim == null) {
			CSVRecord currRecord = (CSVRecord) records.get(lastRecord);
			if(currRecord!=null) {
			    //currRecord.size ++; // detected one more line belonging to the last analyzed record
				currRecord.appendLine(line);
			}
			
		} else {
			
		    System.out.println(	"rocord #" + line.getCurrentLine()
				+ " sku_u: " + line.getField("sku")
				+ ", _attribute_set:"
				+ line.getField("_attribute_set")
			);
			
		    if(!"".equalsIgnoreCase(lastRecord)) {
		    	((CSVRecord) records.get(lastRecord)).isLoaded(true);
		    	
		    }
			lastRecord = line.getField(primKey);

			records.put( lastRecord, new CSVRecord(line) );
		}
	}
*/
	protected void appendLine(CSVLine line) {
		//indexes.split(",");
		
		String prim = line.getField(primKey);
		if ("".equalsIgnoreCase(prim) || prim == null) {
			//CSVRecord currRecord = (CSVRecord) records.get(lastRecord);
			if (lastRecord>-1) {
				CSVRecord currRecord = (CSVRecord) recordsList.get(lastRecord);
				if(currRecord!=null) {
					//currRecord.size ++; // detected one more line belonging to the last analyzed record
					currRecord.appendLine(line);
				}
			}
			
		} else {
			
		    System.out.println(	"rocord #" + line.getCurrentLine()
				+ " sku_u: " + line.getField("sku")
				+ ", _attribute_set:"
				+ line.getField("_attribute_set")
			);
			
		    if(lastRecord>-1) {
		    	((CSVRecord) recordsList.get(lastRecord)).isLoaded(true);
		    	
		    }
			lastRecord = recordsList.size();//line.getField(primKey);
			recordsList.add(new CSVRecord(line));
			//records.put( lastRecord, new CSVRecord(line) );
		}
	}
	
	public void exportToDw () {
		//String stem;
		MappingBase fMapping;
		
		/*
		stem = xmlFile.substring(0, xmlFile.indexOf(".xml") );
		if ( xmlFile.lastIndexOf(".xml", xmlFile.length()) == xmlFile.length()-4) {
			stem = xmlFile.substring(0,   xmlFile.lastIndexOf(".xml", xmlFile.length())   );
		} else {
			stem = xmlFile;
		}*/

		DWInventory xmlInventory = new DWInventory(xmlFolder+"\\inventory.xml",catalogId);
		xmlInventory.StartXmlOutput();

		DWPricebook xmlPricebook = new DWPricebook(xmlFolder+"\\pricebook.xml",catalogId);
		xmlPricebook.StartXmlOutput();
		
		xmlCatalog = new DWCatalog(xmlFolder+"\\catalog.xml",catalogId);
		xmlCatalog.StartXmlOutput();
		
		//parseCSV();
		
		try {
			//this.records = new HashMap();
			csvParser = new CSV(csvFile);
			while (!csvParser.isReady()) {
				CSVLine csvl = csvParser.nextLine();
				if (csvl == null) break;
				//im.appendLine(csvl);
				appendLine(csvl);
				updateCategory(csvl);
			}
		} catch (IOException e) {
			System.err.println("Exception MagentoImportManager.java exportToDw()");
			e.printStackTrace();
		}
		//xmlCatalog.writeNode();
		while (category.hasNext()) {
			xmlCatalog.writeNode(category.next());
		}
		
		//records.entrySet().iterator();
		Iterator<Object> it=recordsList.iterator();
		//DWProduct dwP = new DWProduct(Mapping);
		fMapping = new MappingFromMagento();
		
		DWProduct dwP;
		CSVRecord csvr;
		//DWObject[] DWObjs;
		while(it.hasNext()){
			csvr = (CSVRecord)it.next();
			//xmlInventory.addProductTo();
			dwP=new DWProduct( csvr,fMapping );
			xmlCatalog.writeNode(	dwP.getProductDWObject()	);			//(new DWProduct( (CSVRecord)it.next(),fMapping ) ).getProductDWObject()  );
			//xmlInventory.writeNode(	dwP.getInventoryDWObject()	);
			xmlInventory.writeNode(	xmlInventory.getInventoryDWObject(csvr,fMapping)	);
			xmlPricebook.writeNode(	xmlPricebook.getPricebookDWObject(csvr,fMapping)	);
			
//			DWObjs=dwP.getCategoriesAssigned();
//			for (int i=0,len=DWObjs.length;i<len;i++) {
//				xmlCatalog.writeNode(DWObjs[i]);
//			}
			
		}
		
		DWObject[] DWObjs;
		it=recordsList.iterator();
		while(it.hasNext()){
			//dwP=new DWProduct( (CSVRecord)it.next(),fMapping );
			DWObjs= (new DWProduct( (CSVRecord)it.next(),fMapping ) ).getCategoriesAssigned();
			for (int i=0,len=DWObjs.length;i<len;i++) {
				xmlCatalog.writeNode(DWObjs[i]);
			}
		}
		
		xmlPricebook.FinishXmlOutput();
		xmlCatalog.FinishXmlOutput();
		xmlInventory.FinishXmlOutput();
	}
	
	private void updateCategory(CSVLine line) {

		int len=1,index=0;
		String _category = line.getField("_category");  
		if("".equalsIgnoreCase(_category) || _category==null) {return;}

		while (_category.indexOf("/",index)!=-1) {
			index=_category.indexOf("/",index)+1;
			len++;
		}
		//if (true) return;
		String[] categTree = new String [len];
		categTree = _category.split("/");
		category.put(categTree);
/*		
		for (int i=0;i<len;i++) {
			if (category.get(categTree[i])==null) { // || !category.equals(((Map)category.get(categTree[i])).getClass()) ) {
					category.put(categTree[i],new HashMap());
					System.out.println("Appended new Category:"+categTree[i]+" Depth in tree:"+i);
			}
		}
*/
		
	}
}
